package com.yuanqi.java.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanqi.java.dto.AuditDTO;
import com.yuanqi.java.entity.PurchaseReturnOrder;
import com.yuanqi.java.entity.PurchaseReturnOrderAudit;
import com.yuanqi.java.mapper.PurchaseReturnOrderAuditMapper;
import com.yuanqi.java.mapper.PurchaseReturnOrderMapper;
import com.yuanqi.java.result.AuditResult;
import com.yuanqi.java.result.ReturnOrderStatus;
import com.yuanqi.java.service.IPurchaseReturnOrderAuditService;
import com.yuanqi.java.service.IPurchaseReturnOrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * <p>
 * 采购退货单审核表 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-08-29
 */
/**
 * 采购退货单审核服务实现类
 */
@Service
@RequiredArgsConstructor
public class PurchaseReturnOrderAuditServiceImpl extends ServiceImpl<PurchaseReturnOrderAuditMapper, PurchaseReturnOrderAudit>
        implements IPurchaseReturnOrderAuditService {

    private final IPurchaseReturnOrderService returnOrderService;
    private final PurchaseReturnOrderMapper returnOrderMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void auditReturnOrder(AuditDTO auditDTO) {
        // 检查退货单是否存在
        PurchaseReturnOrder returnOrder = returnOrderMapper.selectById(auditDTO.getReturnOrderId());
        if (returnOrder == null) {
            throw new RuntimeException("退货单不存在");
        }

        // 检查退货单状态
        if (!ReturnOrderStatus.PENDING_AUDIT.getCode().equals(returnOrder.getStatus())) {
            throw new RuntimeException("只有待审核状态的退货单才能审核");
        }

        // 创建审核记录
        PurchaseReturnOrderAudit audit = new PurchaseReturnOrderAudit();
        audit.setReturnOrderId(auditDTO.getReturnOrderId());
        audit.setAuditorId(auditDTO.getAuditorId());
        audit.setAuditTime(LocalDateTime.now());
        audit.setAuditOpinion(auditDTO.getAuditOpinion());
        audit.setAuditResult(auditDTO.getAuditResult());

        // 保存审核记录
        save(audit);

        // 更新退货单状态
        if (AuditResult.APPROVED.getCode().equals(auditDTO.getAuditResult())) {
            returnOrder.setStatus(ReturnOrderStatus.APPROVED.getCode());
        } else {
            returnOrder.setStatus(ReturnOrderStatus.DRAFT.getCode());
        }
        returnOrderMapper.updateById(returnOrder);
    }

    @Override
    public PurchaseReturnOrderAudit getAuditRecord(Long returnOrderId) {
        LambdaQueryWrapper<PurchaseReturnOrderAudit> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PurchaseReturnOrderAudit::getReturnOrderId, returnOrderId)
                .orderByDesc(PurchaseReturnOrderAudit::getAuditTime)
                .last("LIMIT 1");
        return getOne(wrapper);
    }
}